package com.ccsoft.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * 2022年7月11日 13:27:22 BIO通信 server 端
 */
public class Ch09NIOServer {
    public static void main(String[] args) throws IOException {
        //1. 创建 selector
        Selector selector = Selector.open();

        // 2. 创建 channel
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.socket().bind(new InetSocketAddress(6666));
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        // 3. 循环等待客户端连接
        while(true){
            if(selector.select(1000) == 0){// 没有客户端连接，则继续循环监听
                System.out.println("NIO服务端等待了1秒，还没有客户端连接进来。。。");
                continue;
            }

            // 获取关注的事件的集合并循环
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> keyIterator = selectionKeys.iterator();
            while(keyIterator.hasNext()){
                SelectionKey key = keyIterator.next();
                if(key.isAcceptable()){// 是连接事件
                    SocketChannel socketChannel = serverSocketChannel.accept();// 获取事件关联的客户端 channel
                    socketChannel.configureBlocking(false);
                    System.out.println("有客户端连接进来了，socketChannel.hashCode=" + socketChannel.hashCode());
                    socketChannel.register(selector,SelectionKey.OP_READ, ByteBuffer.allocate(1024));// 将 socketChannel 注册到 selector
                }
                if(key.isReadable()){// 发生 OP_READ - 客户端写入了数据，服务端需要读取
                    SocketChannel channel = (SocketChannel) key.channel();
                    ByteBuffer buffer = (ByteBuffer)key.attachment();// 获取该 channel 关联的 buffer
                    channel.read(buffer);
                    String str = new String(buffer.array());
                    System.out.println("从客户端读取的字符串是：" + str);
                }
                // 从事件集合中删除，防止重复操作
                keyIterator.remove();
            }
        }
    }
}
